All files / services pagbankService.js

0% Statements 0/103
0% Branches 0/116
0% Functions 0/10
0% Lines 0/98

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * PagBank Service - Payment Integration (API v4)
 * Handles PagBank payment creation and status checking using the modern REST API
 * 
 * Features:
 * - Creates payment checkouts with shortened URLs (pag.ae/XXXXX)
 * - JSON-based REST API (no more XML)
 * - Simplified authentication (Bearer token)
 * - Real-time status checking
 * 
 * @see https://dev.pagseguro.uol.com.br/reference/checkout-api
 */
 
const axios = require('axios');
const { logger } = require('../config/logger');
 
class PagBankService {
  constructor(email, token, sandbox = true) {
    this.email = email;
    this.token = token;
    this.sandbox = sandbox;
 
    // Validate token
    if (!token || token.trim() === '') {
      throw new Error('PagBank token is required');
    }
 
    // PagBank API v4
    this.baseUrl = sandbox
      ? 'https://sandbox.api.pagseguro.com'
      : 'https://api.pagseguro.com';
    
    logger.info('PagBankService initialized:', {
      hasEmail: !!email,
      hasToken: !!token,
      tokenLength: token?.length,
      sandbox: sandbox,
      baseUrl: this.baseUrl
    });
  }
 
  async createPayment(data) {
    try {
      // Sanitize and validate customer name
      let customerName = 'Default Customer';
      if (data.customer_name && data.customer_name.trim()) {
        customerName = data.customer_name.trim()
          .replace(/[^a-zA-ZÀ-ÿ\s]/g, '')
          .replace(/\s+/g, ' ')
          .substring(0, 50);
        
        const words = customerName.split(' ').filter(w => w.length > 0);
        if (words.length < 2 || customerName.length < 5) {
          customerName = 'Default Customer';
        }
      }
 
      // Format phone for API
      const areaCode = this.getAreaCode(data.customer_phone);
      const phoneNumber = this.formatPhone(data.customer_phone);
 
      // Checkout payload (generates shortened pag.ae link)
      const paymentData = {
        reference_id: data.reference_id || `REF-${Date.now()}`,
        expiration_date: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(), // 24 hours
        customer: {
          name: customerName,
          email: data.customer_email || 'customer@example.com',
          tax_id: '12345678909', // Dummy CPF - can be customized
          phones: [
            {
              country: '55',
              area: areaCode,
              number: phoneNumber,
              type: 'MOBILE'
            }
          ]
        },
        items: [
          {
            reference_id: 'item-1',
            name: (data.description || 'Payment via WhatsApp').substring(0, 100),
            quantity: 1,
            unit_amount: Math.round(data.amount * 100) // Amount in cents
          }
        ],
        notification_urls: [
          `${process.env.BASE_URL || 'http://localhost:3000'}/api/payments/webhook/pagbank`
        ],
        redirect_url: `${process.env.BASE_URL || 'http://localhost:3000'}/payments/success`,
        payment_methods: [
          {
            type: 'CREDIT_CARD'
          },
          {
            type: 'DEBIT_CARD'
          },
          {
            type: 'BOLETO'
          },
          {
            type: 'PIX'
          }
        ],
        payment_methods_configs: [
          {
            type: 'CREDIT_CARD',
            config_options: [
              {
                option: 'INSTALLMENTS_LIMIT',
                value: '12'
              }
            ]
          }
        ]
      };
 
      logger.info('PagBank order data (v4 API):', {
        reference_id: paymentData.reference_id,
        customer_name: customerName,
        amount: data.amount,
        phone: `${areaCode}${phoneNumber}`,
        endpoint: `${this.baseUrl}/orders`,
        hasToken: !!this.token,
        tokenPrefix: this.token ? this.token.substring(0, 8) : 'NO_TOKEN'
      });
 
      const response = await axios.post(
        `${this.baseUrl}/orders`,
        paymentData,
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${this.token}`
          }
        }
      );
 
      // Orders API returns payment links
      if (response.data && response.data.id) {
        // Find payment link
        const paymentLink = response.data.links?.find(link => 
          link.rel === 'PAY' || link.rel === 'SELF'
        );
 
        return {
          success: true,
          payment_id: response.data.id,
          payment_url: paymentLink?.href || response.data.links?.[0]?.href,
          status: 'pending',
          qr_codes: response.data.qr_codes || []
        };
      } else {
        throw new Error('Order ID not found in response');
      }
    } catch (error) {
      logger.error('Error creating PagBank payment:', error);
      logger.error('PagBank error details:', error.response?.data);
      logger.error('Request details:', {
        url: `${this.baseUrl}/orders`,
        hasToken: !!this.token,
        tokenLength: this.token?.length,
        authHeader: this.token ? `Bearer ${this.token.substring(0, 10)}...` : 'NO_TOKEN',
        sandbox: this.sandbox
      });
 
      let errorMessage = 'Error creating PagBank payment';
 
      // Check for authentication errors
      if (error.response?.status === 401 || error.response?.status === 403) {
        logger.error('PagBank authentication failed. Check token.');
        logger.error('Token info:', {
          hasToken: !!this.token,
          tokenLength: this.token?.length,
          tokenPrefix: this.token ? this.token.substring(0, 8) : 'NO_TOKEN',
          sandbox: this.sandbox,
          baseUrl: this.baseUrl
        });
        return {
          success: false,
          error: 'PagBank authentication failed. Please verify your token is correct.',
          details: error.response?.data
        };
      }
 
      if (error.response?.data) {
        // New API returns JSON with error messages
        if (error.response.data.error_messages) {
          errorMessage = error.response.data.error_messages.map(e => e.description).join(', ');
        } else if (error.response.data.message) {
          errorMessage = error.response.data.message;
        }
        
        logger.error('PagBank API response:', error.response.data);
      } else if (error.message) {
        errorMessage = error.message;
      }
 
      return {
        success: false,
        error: errorMessage,
        details: error.response?.data || null
      };
    }
  }
 
  async getPaymentStatus(orderId) {
    try {
      // Query order status
      const response = await axios.get(
        `${this.baseUrl}/orders/${orderId}`,
        {
          headers: {
            'Authorization': `Bearer ${this.token}`
          }
        }
      );
 
      // Orders API returns JSON
      const orderStatus = response.data.status;
      const charges = response.data.charges || [];
      
      let status = 'pending';
      let paid_at = null;
 
      // Map order status
      if (orderStatus === 'PAID') {
        status = 'paid';
        const paidCharge = charges.find(c => c.status === 'PAID');
        if (paidCharge && paidCharge.paid_at) {
          paid_at = new Date(paidCharge.paid_at);
        }
      } else if (orderStatus === 'CANCELED' || orderStatus === 'DECLINED' || orderStatus === 'EXPIRED') {
        status = 'cancelled';
      } else if (orderStatus === 'WAITING' || orderStatus === 'IN_ANALYSIS') {
        status = 'pending';
      } else {
        status = 'pending';
      }
 
      return {
        success: true,
        status: status,
        paid_at: paid_at,
        pagbank_status: orderStatus
      };
    } catch (error) {
      logger.error('Error checking PagBank status:', error);
      return {
        success: false,
        error: error.message || 'Error checking status',
        status: 'pending',
        paid_at: null
      };
    }
  }
 
  async getTransactionByNotification(notificationCode) {
    try {
      // Orders API uses webhooks with direct JSON payload
      const response = await axios.get(
        `${this.baseUrl}/orders/${notificationCode}`,
        {
          headers: {
            'Authorization': `Bearer ${this.token}`
          }
        }
      );
 
      return {
        success: true,
        transaction: response.data
      };
    } catch (error) {
      logger.error('Error fetching PagBank transaction:', error);
      return {
        success: false,
        error: error.message || 'Error fetching transaction'
      };
    }
  }
 
  formatPhone(phone) {
    if (!phone) return '999999999';
    const cleanPhone = phone.replace(/\D/g, '');
 
    // New API expects only the number without area code (8-9 digits)
    if (cleanPhone.length === 11) {
      return cleanPhone.substring(2);
    } else if (cleanPhone.length === 10) {
      return cleanPhone.substring(2);
    } else if (cleanPhone.length === 13 && cleanPhone.startsWith('55')) {
      return cleanPhone.substring(4);
    } else if (cleanPhone.length === 12 && cleanPhone.startsWith('55')) {
      return cleanPhone.substring(4);
    } else if (cleanPhone.length > 13) {
      return cleanPhone.slice(-9);
    } else if (cleanPhone.length >= 8 && cleanPhone.length <= 9) {
      return cleanPhone;
    }
 
    return cleanPhone.length > 9 ? cleanPhone.slice(-9) : cleanPhone;
  }
 
  getAreaCode(phone) {
    if (!phone) return '11';
    const cleanPhone = phone.replace(/\D/g, '');
 
    if (cleanPhone.length === 11) {
      return cleanPhone.substring(0, 2);
    } else if (cleanPhone.length === 10) {
      return cleanPhone.substring(0, 2);
    } else if (cleanPhone.length === 13 && cleanPhone.startsWith('55')) {
      return cleanPhone.substring(2, 4);
    } else if (cleanPhone.length === 12 && cleanPhone.startsWith('55')) {
      return cleanPhone.substring(2, 4);
    } else if (cleanPhone.length > 13) {
      if (cleanPhone.startsWith('55')) {
        return cleanPhone.substring(2, 4);
      }
      return cleanPhone.substring(0, 2);
    }
 
    return '11';
  }
}
 
module.exports = PagBankService;